package com.xr.common.exception;

import com.xr.common.axios.AxiosEnum;
import com.xr.common.axios.AxiosResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 自定义全局异常处理器
 */
@RestControllerAdvice
public class MyGlobalExceptionHandler {

	/**
	 * 处理系统未知异常
	 */
	@ExceptionHandler(Exception.class)
	public AxiosResult handle(Exception e) {
		e.printStackTrace();
		return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
	}

	/**
	 * 处理运行时发生的或主动抛出的其他自定义异常（继承于RuntimeException）
	 */
	@ExceptionHandler(MyCustomException.class)
	public AxiosResult handle(MyCustomException e) {
		e.printStackTrace();
		return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
	}

	/**
	 * 处理字段值重复(违背唯一约束条件)的SQL异常
	 */
	@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
	public AxiosResult handle(SQLIntegrityConstraintViolationException e) {
		e.printStackTrace();
		if (e.getMessage().contains("Duplicate entry")) {
			return AxiosResult.error(AxiosEnum.UNIQUE_ERROR);
		}
		return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
	}

	/**
	 * 处理空指针异常
	 */
	@ExceptionHandler(NullPointerException.class)
	public AxiosResult handle(NullPointerException e) {
		e.printStackTrace();
		return AxiosResult.error(AxiosEnum.NULL_POINTER_ERROR);
	}

}
